//
//  tab_Basket.m
//  VivaModa
//
//  Created by Owly MacBook on 01.02.13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "tab_Basket.h"
#import "basketCell.h"

#import "CryptoSupport.h"

@interface tab_Basket (){
    NSArray *array_products;
    UIButton *login_out;
    UIButton *registration_profil;
}
@property(nonatomic,retain) UILabel *title_label;
@end

@implementation tab_Basket
@synthesize tableView;
@synthesize detailProduct_basket;
@synthesize all_amount;
@synthesize registrationView;
@synthesize profilView;
@synthesize title_label;
@synthesize connection_autorizate;
@synthesize userData;
@synthesize dostavka_label;
@synthesize rub_label;
@synthesize title_amaunt_label;
@synthesize delivery_order;
@synthesize fastOrder;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)getDataFromDB{
    array_products = [SQLiteAccess selectManyRowsWithSQL:@"SELECT * FROM Basket"];
    [self calculateAmount];
}


-(void)calculateAmount{
    if ([array_products count]<1) {
        self.all_amount.text = @"0";
        return;
    }
    int amount = 0;
    for (int i=0; i<[array_products count]; i++) {
        amount = amount + [[[array_products objectAtIndex:i] objectForKey:@"count"] integerValue]*[[[array_products objectAtIndex:i] objectForKey:@"price"] integerValue];
    }
    self.all_amount.text = [NSString stringWithFormat:@"%i",amount];
    
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self getDataFromDB];
    [self.tableView reloadData];
    if ([Singleton sharedMySingleton].neadCheckLogin) {
        [self CheckUserLogin];
        [Singleton sharedMySingleton].neadCheckLogin = NO;
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    //[self.navigationItem setTitle:@"Корзина"];
    [self setNaviganionImg];
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
    barButton.title = @"Назад";
    self.navigationItem.backBarButtonItem = barButton;
    
    
    
    
    
    registration_profil = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 112, 29)];
    [registration_profil setBackgroundImage:[[UIImage imageNamed:@"nav_btn_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [registration_profil setTitle:@" Регистрация " forState:UIControlStateNormal];
    [registration_profil.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [registration_profil setShowsTouchWhenHighlighted:NO];
    [registration_profil addTarget:self action:@selector(switchRegisterView:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *reg_btn = [[UIBarButtonItem alloc] initWithCustomView:registration_profil];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = reg_btn;
    
    
    
    
    login_out = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 55, 29)];
    [login_out setBackgroundImage:[[UIImage imageNamed:@"nav_btn_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [login_out setTitle:@" Войти " forState:UIControlStateNormal];
    [login_out.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [login_out setShowsTouchWhenHighlighted:NO];
    [login_out addTarget:self action:@selector(LogIn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *login_bt = [[UIBarButtonItem alloc] initWithCustomView:login_out];
    self.navigationItem.rightBarButtonItem = login_bt;
    
        
    
    
    self.title_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    self.title_label.backgroundColor = [UIColor clearColor];
    self.title_label.font = [UIFont fontWithName:@"Arial" size:10];
    self.title_label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    self.title_label.textAlignment = UITextAlignmentCenter;
    self.title_label.textColor = [UIColor whiteColor]; // change this color
    self.title_label.numberOfLines = 2;
    
    //self.label.text = [self.navigationItem title];
    
    self.navigationItem.titleView = self.title_label;
    [self CheckUserLogin];
    
    [self.rub_label setFont:[UIFont fontWithName:@"Century Gothic" size:12.0]];
    [self.dostavka_label setFont:[UIFont fontWithName:@"Century Gothic" size:12.0]];
    [self.all_amount setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:30]];
    
    
    [self.title_amaunt_label setFont:[UIFont fontWithName:@"Century Gothic" size:18.0]];
    
    [self.order_button setTitle:@"Оформить" forState:UIControlStateNormal];
    
    [self.order_button.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:16]];
    
    [self.order_button setBackgroundImage:[UIImage imageNamed:@"buy_bg_btn"] forState:UIControlStateNormal];
    [self.order_button setBackgroundImage:[UIImage imageNamed:@"buy_bg_btn_sel"] forState:UIControlStateHighlighted];
    
    //[self.label sizeToFit];
}




-(void)CheckUserLogin{
    if ([Singleton sharedMySingleton].user_login==1) {
        login_out.tag = 1;
        registration_profil.tag = 1;
        [login_out setTitle:@" Выйти " forState:UIControlStateNormal];
        [registration_profil setTitle:@" Личный кабинет " forState:UIControlStateNormal];
        
        self.title_label.text = [NSString stringWithFormat:@"Добро пожаловать, \n %@ !",[Singleton sharedMySingleton].user_name];
    }else{
        login_out.tag = 0;
        registration_profil.tag = 0;
        [login_out setTitle:@" Войти " forState:UIControlStateNormal];
        [registration_profil setTitle:@" Регистрация " forState:UIControlStateNormal];
        self.title_label.text = @"";
    }
}






- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array_products count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"basketCell";
    
    
    
    basketCell *cell = nil;
    cell = (basketCell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"basketCell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[basketCell class]])
            {
                cell = (basketCell *)currentObject;
                break;
            }
        }
    }
    
    
    int price = [[[array_products objectAtIndex:indexPath.row] objectForKey:@"price"] integerValue];
    int count = [[[array_products objectAtIndex:indexPath.row] objectForKey:@"count"] integerValue];
    
    
    cell.name_product.text = [[array_products objectAtIndex:indexPath.row] objectForKey:@"name_product"];
    [cell.name_product setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:14.0]];
    
    
    cell.count.text = [NSString stringWithFormat:@"%i",count];
    cell.price_label.text = [NSString stringWithFormat:@"%i",price];
    cell.all_price.text = [NSString stringWithFormat:@"%i",price*count];
    
    cell.delete_btn.tag = [[[array_products objectAtIndex:indexPath.row] objectForKey:@"id"] integerValue];
    [cell.delete_btn addTarget:self action:@selector(delete_product:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [cell.image_default setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/images/product_images/info_images/%@",[[array_products objectAtIndex:indexPath.row] objectForKey:@"small_image"]]]
                       placeholderImage:[UIImage imageNamed:@"radio_btn_active"]];
    
    
    cell.image_default.layer.masksToBounds = YES;
    [cell.image_default.layer setCornerRadius:8];
    
    
    
    
    UIView *bg = [[UIView alloc] initWithFrame:cell.bounds];
    bg.backgroundColor = [UIColor colorWithRed:125.0/255 green:205.0/255 blue:195.0/255 alpha:1];
    //cell.backgroundView = bg;
    
    UIView *bg_sel = [[UIView alloc] initWithFrame:cell.bounds];
    bg_sel.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = bg_sel;
    
    
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 83;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!detailProduct_basket) {
        detailProduct_basket = [[DetailProduct_basket alloc] initWithNibName:@"DetailProduct_basket" bundle:nil];
    }
    
    detailProduct_basket.id_product = [[[array_products objectAtIndex:indexPath.row] objectForKey:@"id_product"] integerValue];
    detailProduct_basket.name_product = [[array_products objectAtIndex:indexPath.row] objectForKey:@"name_product"];
    detailProduct_basket.name_image = [[array_products objectAtIndex:indexPath.row] objectForKey:@"small_image"];
    detailProduct_basket.price = [[[array_products objectAtIndex:indexPath.row] objectForKey:@"price"]integerValue];
    
    detailProduct_basket.short_description = [[array_products objectAtIndex:indexPath.row] objectForKey:@"short_description"];
    detailProduct_basket.products_quantity = [[array_products objectAtIndex:indexPath.row] objectForKey:@"products_quantity"];
    detailProduct_basket.count_prod = [[array_products objectAtIndex:indexPath.row] objectForKey:@"count"];
    
    detailProduct_basket.needReload = YES;
    [self.navigationController pushViewController:detailProduct_basket animated:YES];
    
}



-(void)delete_product:(id)sender{
    int id_record = [sender tag];
    NSString *name_product = [SQLiteAccess selectOneValueSQL:[NSString stringWithFormat:@"SELECT name_product FROM Basket WHERE id=%i",id_record]];
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:[NSString stringWithFormat:@"Вы действительно хотите удалить %@ с корзины?",name_product]];
    [alert setCancelButtonWithTitle:@"Удалить" block:^{
        [SQLiteAccess deleteWithSQL:[NSString stringWithFormat:@"DELETE FROM Basket WHERE id=%i",id_record]];
        [self getDataFromDB];
        [self.tableView reloadData];
        [[Singleton sharedMySingleton] setBadge];
    }];
    [alert addButtonWithTitle:@"Отмена" block:^{
    }];
    [alert show];
}



-(IBAction)switchRegisterView:(id)sender{
    
    if ([sender tag]!=1) {
        if (!registrationView) {
            registrationView = [[RegistrationView alloc] initWithNibName:@"RegistrationView" bundle:nil];
        }
        [self.navigationController pushViewController:registrationView animated:YES];
    }else{
        if (!profilView) {
            profilView = [[ProfilView alloc] initWithNibName:@"ProfilView" bundle:nil];
        }
        profilView.needReload = YES;
        [self.navigationController pushViewController:profilView animated:YES];
        
    }
}

- (IBAction)LogIn:(id)sender {
    if ([sender tag]!=1) {
        DDAlertPrompt *loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"Войти в систему" delegate:self cancelButtonTitle:@"Отмена" otherButtonTitle:@"Войти"];
        [DDAlertPrompt setBackgroundColor:[UIColor colorWithRed:39.0/255 green:38.0/255 blue:37.0/255 alpha:1]
                        withStrokeColor:[UIColor blackColor]];
        [loginPrompt show];
    }else{
        [UserDefaults setObject:@"" forKey:@"f_name_user"];
        [UserDefaults setObject:@"" forKey:@"s_name_user"];
        [UserDefaults setObject:@"-1" forKey:@"id_user"];
        [UserDefaults setObject:@"" forKey:@"u_adress"];
        [UserDefaults setObject:@"" forKey:@"u_city"];
        [UserDefaults setObject:@"" forKey:@"u_id_country"];
        [UserDefaults setObject:@"" forKey:@"u_id_zone"];
        [[Singleton sharedMySingleton] checkUser];
        [self CheckUserLogin];
    }

}

- (void)didPresentAlertView:(UIAlertView *)alertView {
	if ([alertView isKindOfClass:[DDAlertPrompt class]]) {
		DDAlertPrompt *loginPrompt = (DDAlertPrompt *)alertView;
		[loginPrompt.plainTextField becomeFirstResponder];
		[loginPrompt setNeedsLayout];
	}
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex == [alertView cancelButtonIndex]) {
	} else {
		if ([alertView isKindOfClass:[DDAlertPrompt class]]) {
			DDAlertPrompt *loginPrompt = (DDAlertPrompt *)alertView;
			//NSLog(@"textField: %@", loginPrompt.plainTextField.text);
			//NSLog(@"secretTextField: %@", loginPrompt.secretTextField.text);
            //NSLog(@"MD5:%@", [loginPrompt.secretTextField.text MD5]);

            if ([loginPrompt.plainTextField.text length]>0 && [loginPrompt.secretTextField.text length]>0) {
                [self getDataUserWithLogin:loginPrompt.plainTextField.text andPassword:loginPrompt.secretTextField.text];
            }else{
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка ввода" message:@"Не корректно введены данные."];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                [alert show];
            }
		}
	}
}



-(void)getDataUserWithLogin:(NSString*)login andPassword:(NSString*)password{
    password = [password MD5];
    NSString* params = [NSString stringWithFormat:@"login=%@&password=%@",login,password]; // задаем параметры POST запроса
    
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/login.php"]; // куда отправлять
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
    
    connection_autorizate = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_autorizate) {
        self.userData = [NSMutableData data];
    }
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection == connection_autorizate) {
        [userData appendData:data];
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (connection == connection_autorizate) {
        //NSString *result = [[NSString alloc] initWithData:userData encoding:NSUTF8StringEncoding];
        [self parseJSON:userData];
    }
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data{
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    NSArray * array = [json objectForKey:@"message"];
    //NSLog(@"json = %@",json);
    
    if ([requestResultAutorization integerValue]==1) {
        if ([array count]>0) {
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"user_id"] forKey:@"id_user"];
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"first_name"] forKey:@"f_name_user"];
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"last_name"] forKey:@"s_name_user"];
            
            
            
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"adress"] forKey:@"u_adress"];
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"city"] forKey:@"u_city"];
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"id_country"] forKey:@"u_id_country"];
            [UserDefaults setObject:[[array objectAtIndex:0] objectForKey:@"id_zone"] forKey:@"u_id_zone"];
            
            
            
            
            
            
            
            
            
            
            
            
            [[Singleton sharedMySingleton] checkUser];
            [self CheckUserLogin];
            
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка авторизации"];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            }];
            [alert show];
        }
    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка авторизации, пожалуйста, повторите попытку"];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        }];
        [alert show];
    }
    
    
    
    [self removeActivityView];
    
    
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:0.7];
    
}


- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}

#pragma mark Dejal activity

- (void)displayActivityView
{
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";

}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark

-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}


-(void)setNaviganionImg{
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"navigation_bg"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        
    }
}


-(IBAction)requestOrder:(id)sender{
    
    
    if ([array_products count]>0) {
        if ([Singleton sharedMySingleton].user_login>0) {
            if (!delivery_order) {
                delivery_order = [[deliveryOrder alloc] initWithNibName:@"deliveryOrder" bundle:nil];
            }
            delivery_order.emount = [self.all_amount.text integerValue];
            delivery_order.needReload = YES;
            [self.navigationController pushViewController:delivery_order animated:YES];
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Для оформления заказа необходимо зарегистрироваться и войти под своей учетной записью"];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                
            }];
            [alert addButtonWithTitle:@"Оформить без регистрации" block:^{
                if (!fastOrder) {
                    fastOrder = [[FastOrder alloc] initWithNibName:@"FastOrder" bundle:nil];
                }
                [self.navigationController pushViewController:fastOrder animated:YES];
            }];
            [alert show];
        }

    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Корзина заказов пустая. Для оформления заказа необходимо добавить товар в корзину"];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            
        }];
        [alert show];
    }
    
    

 }


@end
